#include <string.h>
#include <stdio.h>
#include <stdlib.h>

#include "WinSock.h"

#pragma comment(lib,"wsock32.lib")

int
strinst(char * des, const char * s1, const char * s, const char * s2, int size)
{
    int n1 = strlen(s1);
    int n = strlen(s);
    int n2 = strlen(s2);
    if (size < n1 + n2) {
        fprintf(stderr, "No enough memory\n");
        exit(1);
    }
    strcpy(des, s1);
    strcpy(des+n1, s);
    strcpy(des+n+n1, s2);

    return 0;
}

int
strmcat(char * des, const char * src, int *n)
{
    if (*n - strlen(src) < 0) {
        fprintf(stderr, "No enough memory\n");
        exit(1);
    }
    strncat(des, src, *n);
    *n -= strlen(src);
    
    return 0;
}

int
putcmd(SOCKET fd, char * cmd)
{
    int n;
    if ((n = send(fd, cmd, strlen(cmd), 0)) == -1) {
        perror ("send error");
        return (-1);
    }
    return n;
}

int
getreply(SOCKET fd, char * s)
{
    char buff[256];
    int bytes;

    if ((bytes = recv(fd, buff, 256, 0)) == -1) {
        perror("recv error");
        return -1;
    }
    buff[bytes] = '\0';

    puts(buff);

    if (strncmp(buff, s, strlen(s)) != 0) {
		fprintf(stderr, "Reply error: %s\n", buff);
        return -1;
	}
    else
        return 0;
}

int
get_data(SOCKET fd, char * buf, int size)
{
    int bytes;

    if ((bytes = recv(fd, buf, size, 0)) == -1) {
        perror("recv error");
        return -1;
    }
	return bytes;
}

void
sig_get_pipe(int sig)
{
    fprintf(stderr, "Catch SIGPIPE\n");
    exit(1);
}

int
connection(const char *host, int port)
{
    SOCKET sockfd;
    struct sockaddr_in server_addr;
    struct hostent * hp;
    if ((hp = gethostbyname(host)) == NULL) {
		perror("gethostbyname error");
        return -1;
    }

    if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == SOCKET_ERROR ) {
        perror("socket error");
        return -1;
    }

    //signal(SIGPIPE, sig_get_pipe);

    memset(&server_addr, 0, sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(port);
    memcpy(&server_addr.sin_addr, hp->h_addr_list[0], hp->h_length);

    if (connect(sockfd, (LPSOCKADDR)&server_addr, 
			sizeof(struct sockaddr)) == SOCKET_ERROR) {
        perror("connect error");
        return -1;
    }
    

    return sockfd;
}

